<template>
  <div class="app-container">

    <el-card class="box-card">
      <h3>新建备货</h3>
      <div class="container">
        <div class="left">


      <el-form ref="ioralStock" :rules="rules" :model="ioralStock" label-width="150px">
        <el-form-item label="产品批号" prop="batchNumber">
          <!--<el-input v-model="ioralStock.batchNumber"/>-->
          <!--<el-select v-model="ioralStock.batchNumber" clearable :placeholder=chooseBactchNumber>
            <el-option
              v-for="item in optionsBatchNumber"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>-->
          <el-select v-model="ioralStock.batchNumber" clearable placeholder="请选择产品批号" class="custom-width">
            <el-option
              v-for="(value, key) in batchNumbers"
              :key="key"
              :label="value"
              :value="key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用日期" prop="date">
          <!--<el-input v-model="ioralStock.useTime"/>-->
          <el-date-picker
            class="custom-width"
            v-model="ioralStock.useTime"
            type="date"
            placeholder="选择使用日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发货方式" prop="deliveryType">
          <!--<el-input v-model="ioralStock.deliveryType"/>-->
          <el-select v-model="ioralStock.deliveryType" placeholder="请选择运输方式" class="custom-width">
            <el-option
              v-for="item in optionsType"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="件数" prop="pieces">
          <el-input v-model="ioralStock.pieces" @blur="getAllinfo" class="custom-width">
          </el-input>
        </el-form-item>
        <el-form-item label="订量" prop="orderCount">
          <el-input v-model="ioralStock.orderCount" @blur="getAllinfo"  class="custom-width">
            <!--<template slot="append">元</template>-->
          </el-input>
        </el-form-item>
        <el-form-item label="分装体积" prop="volume">
          <el-input v-model="ioralStock.volume" readonly class="custom-width"/>
        </el-form-item>
        <el-form-item label="分装活度" prop="activity" >
          <el-input v-model="ioralStock.activity" readonly class="custom-width"/>
        </el-form-item>
      </el-form>
        </div>
        <div class="right">
<!--          <div class="container2">
            <div class="top">-->

          <el-table v-loading="listLoading" :data="list" size="small" element-loading-text="正在查询中。。。" border fit
                    highlight-current-row >


            <el-table-column align="center" min-width="90" label="产品批号" prop="batchNumber"/>
            <el-table-column align="center" min-width="70" label="序号" prop="id" />
            <el-table-column align="center" min-width="80" label="创建时间" prop="buildTime"/>
<!--            <el-table-column align="center" min-width="70" label="显示Id" prop="showId"/>-->
<!--            <el-table-column align="center" min-width="100" label="收货单位" prop="userName"/>
            <el-table-column align="center" min-width="80" label="发货方式" prop="deliveryType"/>-->
            <el-table-column align="center" min-width="80" label="使用时间" prop="useTime"/>
            <el-table-column align="center" min-width="60" label="件数" prop="pieces"/>

            <el-table-column align="center" min-width="70" label="订量" prop="orderCount" sortable/>
            <!--<el-table-column align="center" min-width="200" label="检定单位" prop="verfier" />-->
            <!--<el-table-column align="center" min-width="200" label="证书编号" prop="vertificateNo" />-->
            <el-table-column align="center" min-width="80" label="分装体积" prop="volume"/>


          </el-table>
<!--            </div>
            <div class="bottom">-->
              <pagination v-show="total>0" :total="total" :page.sync="listQuery2.page" :limit.sync="listQuery2.limit"
                          @pagination="getList"/>
<!--            </div>-->
<!--          </div>-->

        </div>
      </div>
    </el-card>

    <el-card class="box-card">
      <!--<div v-for="o in 4" :key="o" class="text item">
        '' {{'列表内容 ' + o }}
      </div>-->
      <el-table  size="small" :data="productInfo"
                :header-cell-style="{fontSize: '16px', backgroundColor: '#ffff66',color:'#333'}">
        <el-table-column align="center" min-width="60" label="生产日期" prop="date"/>
        <el-table-column align="center" min-width="80" label="产品总活度(Ci)" prop="totalActivity"/>
        <el-table-column align="center" min-width="90" label="产品总体积(ml)" prop="totalVolume"/>
        <el-table-column align="center" min-width="90" label="此次备货活度(Ci)" prop="actualCount"/>
        <el-table-column align="center" min-width="90" label="此次备货体积(ml)" prop="volume"/>
        <el-table-column align="center" min-width="80" label="剩余体积(ml)" prop="remainVolume"/>
        <el-table-column align="center" min-width="80" label="剩余活度(Ci)" prop="remainActivity"/>
      </el-table>

    </el-card>


    <div class="op-container">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handlePublish">新增</el-button>
    </div>

  </div>
</template>

<style>
  .el-card {
    margin-bottom: 10px;
  }

  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .custom-width {
    width: 220px; /* 设置所需的宽度 */
  }
  .container {
    display: flex; /* 启用Flexbox布局 */
  }

  .box {
    flex: 1; /* 让两个div等宽 */
    margin: 10px; /* 可选，为两个div之间添加一些间距 */
  }

  .input-new-keyword {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
  .container2 {
    display: flex;
    flex-direction: column; /* 设置主轴为垂直方向 */
    height: 100vh; /* 容器高度占满整个视口 */
  }
  .top {
    flex: 9; /* 顶部占9份 */
  }
  .bottom {
    flex: 1; /* 底部占1份 */
  }

  .avatar-uploader .el-upload {
    width: 145px;
    height: 145px;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .left {
    width: 30%; /* 或者使用 flex: 2; 来分配空间 */
    margin: 10px;
    /*background-color: lightblue; !* 仅用于视觉区分 *!*/
  }
  .right {
    width: 70%; /* 或者使用 flex: 8; 来分配空间 */
    margin: 10px;
    /*background-color: lightcoral; !* 仅用于视觉区分 *!*/
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
  }

  .avatar {
    width: 145px;
    height: 145px;
    display: block;
  }
</style>

<script>
// eslint-disable-next-line no-unused-vars

import { publishiorderStock, listCatAndBrand, formatterTime,listiorderStocks } from '@/api/business/iorderStock'
import { createStorage, uploadPath } from '@/api/business/storage'
import { listBachNumbers,getInfoByOrderCount,listBachNumbers2} from '@/api/business/productProduction'
import Editor from '@tinymce/tinymce-vue'
import { MessageBox } from 'element-ui'
import { getToken } from '@/utils/auth'
import BackToTop from '@/components/BackToTop'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
// eslint-disable-next-line no-unused-vars
import { myformatdate } from '@/api/business/iorderStock'
export default {
  name: 'iorderStockCreate',
  components: { Editor,BackToTop, Pagination },

  data() {
    return {
      uploadPath,
      newKeywordVisible: false,
      newKeyword: '',
      keywords: [],
      productInfo:[],
      categoryList: [],
      listLoading: true,
      loading: false,
      brandList: [],
      optionsBatchNumber:[],
      chooseBactchNumber:'请选择产品批号',
      ioralStock: [],
      batchNumbers:[],
      specVisiable: false,
      specForm: { specification: '', value: '', picUrl: '' },
      multipleSpec: false,
      specifications: [{ specification: '规格', value: '标准', picUrl: '' }],
      productVisiable: false,
      listQuery: {
        batchNumber: '',
        orderCount: '',
        useTime: '',
        piece:0,
        splitQuantity:'',
        activity:'',
        deliveryType:''},
      listQuery2: {
        ioralRaw: {},
        page: 1,
        size: '20',
        batchNumber: '',
        startToEnd: [],
        sort: 'purchase_date',
        order: 'desc',
        isNew:0
      },
      products: [{ id: 0, specifications: ['标准'], price: 0.00, number: 0, url: '' }],
      attributeVisiable: false,
      attributeForm: { attribute: '', value: '' },
      attributes: [],

      optionsType: [{
        value: '空运',
        label: '空运'
      }, {
        value: '汽运',
        label: '汽运'
      }, {
        value: '铁运',
        label: '铁运'
      }],
      rules: {
        iorderStockNumber: [{ required: true, message: '文档编号不能为空', trigger: 'blur' }],
        iorderStockName: [{ required: true, message: '文档名称不能为空', trigger: 'blur' }],
        userDepartments: [{ required: true, message: '使用部门不能为空', trigger: 'blur' }]
      },
      editorInit: {
        language: 'zh_CN',
        convert_urls: false,
        plugins: ['advlist anchor autolink autosave code codesample colorpicker colorpicker contextmenu directionality emoticons fullscreen hr image imagetools importcss insertdatetime link lists media nonbreaking noneditable pagebreak paste preview print save searchreplace spellchecker tabfocus table template textcolor textpattern visualblocks visualchars wordcount'],
        toolbar: ['searchreplace bold italic underline strikethrough alignleft aligncenter alignright outdent indent  blockquote undo redo removeformat subscript superscript code codesample', 'hr bullist numlist link image charmap preview anchor pagebreak insertdatetime media table emoticons forecolor backcolor fullscreen'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          createStorage(formData).then(res => {
            success(res.data.data.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      }
    }
  },
  computed: {
    headers() {
      return {
        'X-Dts-Admin-Token': getToken()
      }
    }
  },
  created() {
    this.getBatchNumbers()
    this.getList()
  },
  mounted(){
    this.getBatchNumbers()
  },

  methods: {
    init: function() {
      listCatAndBrand().then(response => {
        this.categoryList = response.data.data.categoryList
        this.brandList = response.data.data.brandList
      })
    },
    handleCategoryChange(value) {
      this.ioralStock.categoryId = value[value.length - 1]
    },
    handleCancel: function() {
      this.$router.push({ path: '/iorders/list4' })
    },
    changePlaceholder(newPlaceholder) {
      this.inputPlaceholder = newPlaceholder;
    },
    getBatchNumbers() {
      listBachNumbers2(this.listQuery).then(response => {
        this.batchNumbers = response.data.data.batchNumbers/*.sort((a, b) => new Date(a) - new Date(b))*/
        /*     this.batchNumbers=this.batchNumbers2.slice().reverse()*/
        /*  this.batchNumbers2=this.batchNumbers.sort((a, b) => new Date(a) - new Date(b))*/
      }).catch(() => {
        console.log('getList catch')
        /*this.listStockss = []
        /!*this.total1 = 0*!/
        this.listLoading = false*/
      })

    },
    getList() {
      this.listLoading = true
      const stockQuery = {
        page: this.listQuery2.page,
        limit: this.listQuery2.limit,
        batchNumber:'',
        sort:'build_time',
        order:'desc',
      };
      listiorderStocks(this.listQuery2).then(response => {
        this.list = response.data.data.items
        this.total = response.data.data.total
        this.listLoading = false
      }).catch(() => {
        this.list = []
        this.total = 0
        this.listLoading = false
      })
    },
    handlePublish: function() {
      // eslint-disable-next-line no-undef
      console.log(this.ioralStock);
      const finaliorderStock = {

        ioralStock: this.ioralStock/*,
        specifications: this.specifications,w
        products: this.products,
        attributes: this.attributes*/
      }
      this.listQuery.batchNumber=this.ioralStock.batchNumber
      this.listQuery.orderCount=this.ioralStock.orderCount
      this.listQuery.useTime=this.ioralStock.useTime
      this.listQuery.piece=this.ioralStock.pieces
      this.listQuery.deliveryType=this.ioralStock.deliveryType
      this.listQuery.splitQuantity=this.ioralStock.volume
      this.listQuery.activity=this.ioralStock.activity
      publishiorderStock(this.listQuery).then(response => {
        this.productInfo=response.data.data.items
        this.getList()
        this.$notify.success({
          title: '成功',
          message: '创建成功'
        })
        this.$router.push({ path: '/iorders/list7' })
      }).catch(response => {
        MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
          confirmButtonText: '确定',
          type: 'error'
        })
      })
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
      this.iorderStock.keywords = this.keywords.toString()
    },
    showInput() {
      this.newKeywordVisible = true
      this.$nextTick(_ => {
        this.$refs.newKeywordInput.$refs.input.focus()
      })
    },
    getAllinfo(){
      this.listQuery.batchNumber=this.ioralStock.batchNumber
      this.listQuery.orderCount=this.ioralStock.orderCount
      this.listQuery.useTime=this.ioralStock.useTime
      this.listQuery.piece=this.ioralStock.pieces
      getInfoByOrderCount(this.listQuery).then(response=>{
                 this.productInfo=response.data.data.productInfo
                 this.ioralStock.volume=response.data.data.volume
                 this.ioralStock.activity=response.data.data.activity
                /* if(response.data.data.remainActivity<=0){
                   MessageBox.alert('剩余体积（活度）不足：' + response.data.data.remainActivity, '警告', {
                     confirmButtonText: '确定',
                     type: 'error'
                   })
                 }*/
      }).catch(() => {
        console.log('业务错误')
        /*this.listStockss = []
        /!*this.total1 = 0*!/
        this.listLoading = false*/
      })
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword
      if (newKeyword) {
        this.keywords.push(newKeyword)
        this.iorderStock.keywords = this.keywords.toString()
      }
      this.newKeywordVisible = false
      this.newKeyword = ''
    },
    uploadPicUrl: function(response) {
      this.iorderStock.picUrl = response.data.url
    },
    uploadOverrun: function() {
      this.$message({
        type: 'error',
        message: '上传订单个数超出限制!最多上传5张图片!'
      })
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.iorderStock.gallery.push(response.data.url)
      }
    },
    handleRemove: function(file, fileList) {
      for (var i = 0; i < this.iorderStock.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url
        if (file.response === undefined) {
          url = file.url
        } else {
          url = file.response.data.url
        }

        if (this.iorderStock.gallery[i] === url) {
          this.iorderStock.gallery.splice(i, 1)
        }
      }
    },
    specChanged: function(label) {
      if (label === false) {
        this.specifications = [{ specification: '规格', value: '标准', picUrl: '' }]
        this.products = [{ id: 0, specifications: ['标准'], price: 0.00, number: 0, url: '' }]
      } else {
        this.specifications = []
        this.products = []
      }
    },
    uploadSpecPicUrl: function(response) {
      this.specForm.picUrl = response.data.url
    },
    handleSpecificationShow() {
      this.specForm = { specification: '', value: '', picUrl: '' }
      this.specVisiable = true
    },
    handleSpecificationAdd() {
      var index = this.specifications.length - 1
      for (var i = 0; i < this.specifications.length; i++) {
        const v = this.specifications[i]
        if (v.specification === this.specForm.specification) {
          index = i
        }
      }

      this.specifications.splice(index + 1, 0, this.specForm)
      this.specVisiable = false

      this.specToProduct()
    },
    handleSpecificationDelete(row) {
      const index = this.specifications.indexOf(row)
      this.specifications.splice(index, 1)
      this.specToProduct()
    },
    specToProduct() {
      if (this.specifications.length === 0) {
        return
      }
      // 根据specifications创建临时规格列表
      var specValues = []
      var spec = this.specifications[0].specification
      var values = []
      values.push(0)

      for (var i = 1; i < this.specifications.length; i++) {
        const aspec = this.specifications[i].specification

        if (aspec === spec) {
          values.push(i)
        } else {
          specValues.push(values)
          spec = aspec
          values = []
          values.push(i)
        }
      }
      specValues.push(values)

      // 根据临时规格列表生产货品规格
      // 算法基于 https://blog.csdn.net/tyhj_sf/article/details/53893125
      var productsIndex = 0
      var products = []
      var combination = []
      var n = specValues.length
      for (var s = 0; s < n; s++) {
        combination[s] = 0
      }
      var index = 0
      var isContinue = false
      do {
        var specifications = []
        for (var x = 0; x < n; x++) {
          var z = specValues[x][combination[x]]
          specifications.push(this.specifications[z].value)
        }
        products[productsIndex] = { id: productsIndex, specifications: specifications, price: 0.00, number: 0, url: '' }
        productsIndex++

        index++
        combination[n - 1] = index
        for (var j = n - 1; j >= 0; j--) {
          if (combination[j] >= specValues[j].length) {
            combination[j] = 0
            index = 0
            if (j - 1 >= 0) {
              combination[j - 1] = combination[j - 1] + 1
            }
          }
        }
        isContinue = false
        for (var p = 0; p < n; p++) {
          if (combination[p] !== 0) {
            isContinue = true
          }
        }
      } while (isContinue)

      this.products = products
    },
    handleProductShow(row) {
      this.productForm = Object.assign({}, row)
      this.productVisiable = true
    },
    uploadProductUrl: function(response) {
      this.productForm.url = response.data.url
    },
    handleProductEdit() {
      for (var i = 0; i < this.products.length; i++) {
        const v = this.products[i]
        if (v.id === this.productForm.id) {
          this.products.splice(i, 1, this.productForm)
          break
        }
      }
      this.productVisiable = false
    },
    handleAttributeShow() {
      this.attributeForm = {}
      this.attributeVisiable = true
    },
    handleAttributeAdd() {
      this.attributes.unshift(this.attributeForm)
      this.attributeVisiable = false
    },
    handleAttributeDelete(row) {
      const index = this.attributes.indexOf(row)
      this.attributes.splice(index, 1)
    }
  }
}
</script>
